package com.sky.service.impl;

import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkSpaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {
    @Autowired
    private  OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkSpaceService workSpaceService;

    /**
     * 营业额统计
     * @param begin
     * @param end
     * @return
     */
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        // 通过时间范围查询数据库，获取营业额数据
        // 存放开始日期和结束日期的集合
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            // 日期计算，计算指定日期的下一天对应的日期
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        // 需要使用long3包下的StringUtils工具类，将list转化为字符串，用逗号分隔
        String dateListString = StringUtils.join(dateList, ",");
        // 存放每天的营业额
        List<Double> turnoverList = new ArrayList<>();
        for(LocalDate date: dateList) {
            // 查询date日期对应的营业额数据，营业额是指“已完成”的订单金额统计
            // 获取当前时间的当天零点以及当天的23:59:59.999999999的时间
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            map.put("begin", beginTime);
            map.put("end", endTime);
            map.put("status", Orders.COMPLETED);
            Double turnover = orderMapper.sumByMap(map);
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
        }
        // 将list转化为字符串，用逗号分隔
        String turnoverListString = StringUtils.join(turnoverList, ",");


        TurnoverReportVO turnoverReportVO = new TurnoverReportVO();
        turnoverReportVO.setDateList(dateListString);
        turnoverReportVO.setTurnoverList(turnoverListString);

        return turnoverReportVO;
    }

    /**
     * 实现用户统计
     * @param begin
     * @param end
     * @return
     */
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        // 获取时间范围内的所有日期存入List
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while(!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        log.info("时间日期列表", dateList);
        // 存放每天新增的用户数list
        List<Integer> addUserList = new ArrayList<>();
        // 存放当前日期前的所有用户总数量
        List<Integer> allUserList = new ArrayList<>();
        // 遍历日期
        for(LocalDate date : dateList) {
            // 获取起始日期的零点
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            // 获取末时间的23:59:59.999999999
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            // 定义Map
            Map map = new HashMap();
            map.put("end", endTime);
            // 调用mapper
            Integer allSum = userMapper.sumByMap(map);
            map.put("begin", beginTime);
            Integer addSum = userMapper.sumByMap(map);
            addUserList.add(addSum);
            allUserList.add(allSum);
        }
        // 将list转化为字符串，用逗号分隔并封装为给前端的VO对象
        String dateListString = StringUtils.join(dateList, ",");
        String addUserListString = StringUtils.join(addUserList, ",");
        String allUserListString = StringUtils.join(allUserList, ",");
        UserReportVO userReportVO = new UserReportVO();
        userReportVO.setDateList(dateListString);
        userReportVO.setNewUserList(addUserListString);
        userReportVO.setTotalUserList(allUserListString);
        return userReportVO;
    }

    /**
     * 实现订单统计
     * @param begin
     * @param end
     * @return
     */
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        // 存放每天的订单数
        List<Integer> orderCountList = new ArrayList<>();
        // 存放每天的有效订单数
        List<Integer> validOrderCountList = new ArrayList<>();
        for(LocalDate date :dateList) {
            // 获取起始日期的零点
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            // 获取末时间的23:59:59.999999999
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            // 定义Map
            Map map = new HashMap();
            map.put("begin", beginTime);
            map.put("end", endTime);
            // 调用mapper,获取每天的订单数
            Integer orderCount = orderMapper.sumOrderByMap(map);
            map.put("status", Orders.COMPLETED);
            // 调用mapper,获取每天的有效订单数
            Integer validOrderCount = orderMapper.sumOrderByMap(map);
            orderCountList.add(orderCount);
            validOrderCountList.add(validOrderCount);
        }
        // 将list转化为字符串，用逗号分隔并封装为给前端的VO对象
        String dateListString = StringUtils.join(dateList, ",");
        String orderCountListString = StringUtils.join(orderCountList, ",");
        String validOrderCountListString = StringUtils.join(validOrderCountList, ",");
        Map map = new HashMap();
        map.put("begin", begin);
        map.put("end", end);
        map.put("status", Orders.COMPLETED);
        // 获取订单总数
        Integer totalOrderCount = orderMapper.sumOrderByMap(null);
        // 获取有效订单数(订单已完成)
        Integer validOrderCount = orderMapper.sumOrderByMap(map);
        // 计算订单完成率
        Double orderCompletionRate = (validOrderCount * 1.0) / (totalOrderCount * 1.0);
        OrderReportVO orderReportVO = new OrderReportVO();
        orderReportVO.setDateList(dateListString);
        orderReportVO.setOrderCountList(orderCountListString);
        orderReportVO.setValidOrderCountList(validOrderCountListString);
        orderReportVO.setTotalOrderCount(totalOrderCount);
        orderReportVO.setValidOrderCount(validOrderCount);
        orderReportVO.setOrderCompletionRate(orderCompletionRate);
        return orderReportVO;
    }

    /**
     * 实现销量排名前10统计
     * @param begin
     * @param end
     * @return
     */
    public SalesTop10ReportVO getTop10(LocalDate begin, LocalDate end) {
        // 存放商品名称列表
        List<String> nameList = new ArrayList<>();
        // 存放商品数量列表
        List<Integer> numberList = new ArrayList<>();

        // 获取起始日期的零点
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        // 获取末时间的23:59:59.999999999
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        Map map = new HashMap();
        map.put("begin", beginTime);
        map.put("end", endTime);
        map.put("status", Orders.COMPLETED);
        List<OrderDetail> orderDetailList = orderMapper.getSalesTop10ByDate(map);
        orderDetailList.forEach(orderDetail -> {
            nameList.add(orderDetail.getName());
            numberList.add(orderDetail.getNumber());
        });
        // 将list转化为字符串，用逗号分隔并封装为给前端的VO对象
        String nameListString = StringUtils.join(nameList, ",");
        String numberListString = StringUtils.join(numberList, ",");
        SalesTop10ReportVO salesTop10ReportVO = new SalesTop10ReportVO();
        salesTop10ReportVO.setNameList(nameListString);
        salesTop10ReportVO.setNumberList(numberListString);
        return salesTop10ReportVO;
    }

    /**
     * 导出运营数据报表
     * @param response
     */
    public void exportBusinessData(HttpServletResponse response) {
        // 1. 查询数据库，获取营业数据 -- 查询最近30天的运行数据
        LocalDate date = LocalDate.now();
        LocalDate begin = date.minusDays(30); // 30天前
        LocalDate end = date.minusDays(1); // 昨天
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        // 查询概览数据
        BusinessDataVO businessDataVO = workSpaceService.businessData(beginTime, endTime);

        // 2. 通过POI将数据写入Excel文件中
        InputStream stream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            // 基于模板文件创建一个新的Excel文件
            XSSFWorkbook excel = new XSSFWorkbook(stream);

            // 填充数据
            // 获取标签页
            XSSFSheet sheet1 = excel.getSheet("Sheet1");
            // 填充数据 - 时间 （在表格文件的第二行第二个单元格）
            sheet1.getRow(1).getCell(1).setCellValue("时间：" + begin + "至" + end);

            // 填充数据 - 概览数据
            // 获得第4行
            XSSFRow row3 = sheet1.getRow(3);
            row3.getCell(2).setCellValue(businessDataVO.getTurnover()); // 营业额数据
            row3.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate()); // 订单完成率
            row3.getCell(6).setCellValue(businessDataVO.getNewUsers()); // 新增用户数
            // 获得第5行并插入数据（这是上边的简写方法）
            sheet1.getRow(4).getCell(2).setCellValue(businessDataVO.getValidOrderCount()); // 有效订单
            sheet1.getRow(4).getCell(4).setCellValue(businessDataVO.getUnitPrice()); // 平均客单价


            // 填充明细数据（30天的）
            for(int i = 0; i < 30; i++) {
                // 首先获取30天前的那天的数据，然后依次向后填充
                LocalDate currentDate = begin.plusDays(i);
                // 查询当天的营业额数据
                BusinessDataVO businessCurrentData = workSpaceService.businessData(LocalDateTime.of(currentDate, LocalTime.MIN), LocalDateTime.of(currentDate, LocalTime.MAX));
                // 获取第i + 7 行
                XSSFRow currentRow = sheet1.getRow(i + 7);
                currentRow.getCell(1).setCellValue(currentDate.toString());
                currentRow.getCell(2).setCellValue(businessCurrentData.getTurnover());
                currentRow.getCell(3).setCellValue(businessCurrentData.getValidOrderCount());
                currentRow.getCell(4).setCellValue(businessCurrentData.getOrderCompletionRate());
                currentRow.getCell(5).setCellValue(businessCurrentData.getUnitPrice());
                currentRow.getCell(6).setCellValue(businessCurrentData.getNewUsers());
            }


            // 3. 通过输出流将Excel文件下载到客户端浏览器中
            // 获得输出流对象
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            // 4. 关闭流
            out.close();
            excel.close();
            stream.close();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }
}
